package com.binguo.api.service;

import com.alibaba.fastjson.JSONObject;
import com.binguo.common.util.UrlUtils;
import com.binguo.model.api.vo.OrderItemVO;
import com.binguo.model.api.vo.OrderVO;
import com.binguo.model.model.BinguoOrder;
import com.binguo.service.OrderService;
import com.binguo.transfer.OrderVOTransfer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * NutrientsSyncService
 *
 * @author : Moore(hemw)
 * @date : 2020-07-03
 */
@Service
public class NutrientsSyncService {

    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(NutrientsSyncService.class);

    @Resource
    private OrderService orderService;

    @Resource
    private OrderVOTransfer orderVoTransfer;

    @Value(value = "${nutrients.save.order.url}")
    private String url;

    /**
     * 根据订单vo进行营养数据同步
     *
     * @param orderVO
     */
    public void nutrientsSyncByVO(OrderVO orderVO) {
        if (orderVO == null) {
            LOGGER.error("1.record nutrients data by vo,order vo is null");
            return;
        }
        if (StringUtils.isBlank(orderVO.getOrderNo())) {
            LOGGER.error("2.record nutrients data by vo, order no is null");
            return;
        }
        if (orderVO.getOrderItems() == null || orderVO.getOrderItems().isEmpty()) {
            LOGGER.error("3.record nutrients data by vo,order item is null,order no :{}", orderVO.getOrderNo());
            return;
        }
        Optional<BinguoOrder> binguoOrder = orderService.findByOrderNo(orderVO.getOrderNo());
        if (!binguoOrder.isPresent()) {
            LOGGER.error("4.record nutrients data by vo,order do is null,order no :{}", orderVO.getOrderNo());
            return;
        }
        List<Integer> itemIds = new ArrayList<>();
        for (OrderItemVO orderItem : orderVO.getOrderItems()) {
            itemIds.add(orderItem.getProductId());
        }
        doSyncData(binguoOrder.get(), itemIds);
    }

    /**
     * 根据订单号进行营养数据同步
     *
     * @param orderNo
     */
    public void nutrientsSyncByOrderNo(String orderNo) {
        if (StringUtils.isBlank(orderNo)) {
            LOGGER.error("1.record nutrients data by order no, order no is null");
            return;
        }
        Optional<BinguoOrder> binguoOrder = orderService.findByOrderNo(orderNo);
        if (!binguoOrder.isPresent()) {
            LOGGER.error("2.record nutrients data by order no,order do is null,order no :{}", orderNo);
            return;
        }
        List<OrderItemVO> orderItems = orderVoTransfer.getOrderItemListByOrderNo(orderNo);
        if (orderItems == null || orderItems.isEmpty()) {
            LOGGER.error("3.record nutrients data by order no,order item is null,order no :{}", orderNo);
            return;
        }
        List<Integer> itemIds = new ArrayList<>();
        for (OrderItemVO orderItem : orderItems) {
            itemIds.add(orderItem.getProductId());
        }
        doSyncData(binguoOrder.get(), itemIds);
    }

    /**
     * 执行数据同步
     *
     * @param orderDO
     * @param itemIds
     */
    private void doSyncData(BinguoOrder orderDO, List<Integer> itemIds) {
        LOGGER.info("record nutrients data start,order no:{}", orderDO.getOrderno());
        JSONObject parameter = new JSONObject();
        parameter.put("orderId", orderDO.getId());
        parameter.put("orderCode", orderDO.getOrderno());
        parameter.put("dishesIds", itemIds);
        parameter.put("merchantId", orderDO.getShopid());
        parameter.put("consumerId", orderDO.getCustomerid());
        Date createTime = orderDO.getCreated();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(createTime.toInstant(), ZoneId.systemDefault());
        int hour = localDateTime.getHour();
        int mealType = 0;
        //餐断判定
        if (hour >= 3 && hour < 10) {
            mealType = 1;
        } else if (hour >= 10 && hour < 15) {
            mealType = 2;
        } else if (hour >= 15 && hour < 22) {
            mealType = 3;
        } else {
            mealType = 4;
        }
        parameter.put("mealType", mealType);
        try {
            String result = UrlUtils.send(url, parameter, "utf-8");
            if (StringUtils.isBlank(result)) {
                LOGGER.error("1.record nutrients data,result is null,data:{}", parameter);
                return;
            }
            JSONObject resultJson = JSONObject.parseObject(result);
            if (resultJson == null) {
                LOGGER.error("2.record nutrients data,result json is null,data:{}", parameter);
                return;
            }
            String code = resultJson.getString("code");
            if (StringUtils.isBlank(code)) {
                LOGGER.error("3.record nutrients data,result code is null,data:{},result:{}", parameter, result);
            }
            if (!"200".equals(code)) {
                LOGGER.error("4.record nutrients data,result code is failed,data:{},result:{}", parameter, result);
                return;
            }
            LOGGER.info("record nutrients data success,order no :{}", orderDO.getOrderno());
        } catch (Throwable th) {
            LOGGER.error("5.record nutrients data error,data:{},ex :", parameter, th);
        }
    }
}
